#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>

using namespace std;

#define NUM 5

pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;

int cnt = 0;

class ThreadData
{
public:
    ThreadData(int i)
    {
        _threadname = "thread " + to_string(i);
    }

public:
    string _threadname;
};

void *Count(void *args)
{
    pthread_detach(pthread_self());

    ThreadData *td = static_cast<ThreadData *>(args);
    while (true)
    {   
        pthread_mutex_lock(&lock);
        pthread_cond_wait(&cond,&lock); //进入等待队列之前会释放锁
        cout << td->_threadname << ", "<< "cnt = " << cnt++ << endl;
        usleep(10000);
        pthread_mutex_unlock(&lock);
    }

    return nullptr;
}


int main()
{
    for (int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        ThreadData *td = new ThreadData(i + 1);
        pthread_create(&tid, nullptr, Count, td);
    }

    while (true)
    {
        pthread_cond_signal(&cond);
        sleep(2);
    }

    return 0;
}